#include <stdio.h>
#include <stdbool.h>
#include <string.h>

#define MEM_SIZE 8192
#define NUM_BLOCKS 8

char BUFF[MEM_SIZE];

// 预置的内存分配块大小
const int block_sizes[NUM_BLOCKS] = {8, 16, 32, 64, 128, 256, 512, 1024};

// 内存块的元数据结构
typedef struct {
    bool used;
    int size;
    char *ptr;
} Block;

Block blocks[NUM_BLOCKS];

// 初始化内存管理系统
void init_memory() {
    int offset = 0;
    for (int i = 0; i < NUM_BLOCKS; i++) {
        blocks[i].used = false;
        blocks[i].size = block_sizes[i];
        blocks[i].ptr = BUFF + offset;
        offset += block_sizes[i];
    }
}

// 模拟 malloc 函数
void *mmalloc(int size) {
    for (int i = 0; i < NUM_BLOCKS; i++) {
        if (!blocks[i].used && blocks[i].size >= size) {
            blocks[i].used = true;
            printf("Allocated %d bytes at %p\n", size, (void *)blocks[i].ptr);
            return blocks[i].ptr;
        }
    }
    printf("Failed to allocate %d bytes\n", size);
    return NULL;
}

// 模拟 free 函数
void mfree(void *ptr) {
    for (int i = 0; i < NUM_BLOCKS; i++) {
        if (blocks[i].ptr == ptr) {
            blocks[i].used = false;
            printf("Freed memory at %p\n", ptr);
            return;
        }
    }
    printf("Invalid free request at %p\n", ptr);
}

int main() {
    init_memory();

    // 测试内存分配和释放
    void *p1 = mmalloc(16);
    void *p2 = mmalloc(64);
    void *p3 = mmalloc(128);

    mfree(p2);
    mfree(p1);
    mfree(p3);

    return 0;
}